#coding=utf-8
#!/usr/bin/env python
#
# Copyright 2007 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
from google.appengine.ext import webapp
from google.appengine.ext.webapp import util
from google.appengine.api import users
##from google.appengine.api.users import createNewUserConfirmation
from google.appengine.api import mail
import time


class MainHandler(webapp.RequestHandler):
##    def get(self):
##        user=users.get_current_user()
##        if user:
##            self.response.headers['Content-Type']='text/plain'
##            self.response.out.write('Hello, ' + user.nickname())
##        else:
##            self.redirect(users.create_login_url(self.request.uri))
    def get(self):
        self.response.out.write('''
<html>
   <body>
       <form action="/sendmail" method="post">
           <div><textarea name="email_subject" rows="1" cols="60"></textarea></div>
           <div><textarea name="email_text" rows="3" cols="60"></textarea></div>
           <div><textarea name="email_address" rows="1" cols="27"></textarea></div>
           <div><input type="submit" value="send mail"></div>
       </form>
   </body>
</html>''')


class SendMail(webapp.RequestHandler):
    def post(self):
        text=self.request.get("email_text")
        user_address=self.request.get("email_address")
        sub=self.request.get("email_subject")
        if not mail.is_email_valid(user_address):
            self.response.out.write('Not a valid email address')
        else:
##            sender_address="yjx527@gmail.com"
##            body=text
            message=mail.EmailMessage(sender='yjx527@gmail.com',
                                      subject=sub)
            #message.to=user_address
            message.to=user_address
            message.html=text

##            mail.send_mail(sender_address,user_address,subject,body)
            message.send()
            self.response.out.write('Email has been sent. Redirecting to main page...')
            self.response.out.write('<meta http-equiv="refresh" content="3;url=/">')


def main():
    application = webapp.WSGIApplication([('/', MainHandler),
                                          ('/sendmail',SendMail)],
                                         debug=True)
    util.run_wsgi_app(application)


if __name__ == '__main__':
    main()
##print 'Content-Type: text/plain'print ''print 'Hello, world!'





